package util;

import constant.Constant;
import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.openqa.selenium.By;
import util.tools.BusinessTools;
import util.tools.CommonTools;

import java.io.InputStream;
import java.net.URI;
import java.util.*;

/**
 * Created by chenkuo on 2017/8/9.
 * http相关
 */


public class HttpClient {

/**获取Admin与Cs的cookie*/
    public static String getCsAdminCookie (String url,Map<String,String> map)throws Exception{
        String cookie = null;
        CloseableHttpResponse response = post(url, map);
        Header[] allHeaders = response.getAllHeaders();
        for (int i = 0; i< allHeaders.length;i++){
            String str = allHeaders[i].getValue();
//            System.out.println("abc----->"+str);
            if (str.contains("rsid=")){
                cookie = allHeaders[i].getValue().substring(str.indexOf("rsid="),str.indexOf("Path=/"));
//                System.out.println("cookie="+cookie);
            }
        }
        return cookie;
    }

    /**获取Admin的cookie*/
    public static String getAdminCookie() throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        map.put("username", Constant.SYSTEMUSER);
        map.put("password",Constant.SYSTEMPASSWORD);
        map.put("remember","true");
        map.put("captchaKey","85306534-4490-6197-9086-1516019777328");
        map.put("captcha",BusinessTools.buildPicCaptcha());
        String cookie = HttpClient.getCsAdminCookie(Constant.adminLogin,map);
        return cookie;
}
    /**获取Cs的cookie*/
    public static String getCsCookie() throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        map.put("username", Constant.SYSTEMUSER);
        map.put("password", Constant.SYSTEMPASSWORD);
        map.put("captchaKey", "61949994-5806-5107-2882-1502251117496");
        map.put("captcha", BusinessTools.buildPicCaptcha());
        String cookie = HttpClient.getCsAdminCookie(Constant.httpCsUrl, map);
        return cookie;
    }
    /**带着cookie访问链接post*/

    public static CloseableHttpResponse post(String url,Map<String,String> map,Map<String,String> headMap){
        CloseableHttpResponse response = null;
        try {
            CloseableHttpClient client = HttpClients.createDefault();

            HttpPost post = new HttpPost();
            post.setURI(new URI(url));
            List<NameValuePair> getParams = getParamsList(map);
            setHeader(post, headMap);

            UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(
                getParams, "UTF-8");
            post.setEntity(postEntity);
            response = client.execute(post);
            InputStream content = response.getEntity().getContent();
            byte[] bytes = new byte[1024];
            int size = 0;
            while ((size = content.read(bytes)) != -1){
                System.out.println(new String(bytes,0,size));
            }

        } catch (Exception e) {
        }
        return response;
    }




    private static List<NameValuePair>  getParamsList(Map<String,String> map){
        List<NameValuePair> paramList = new ArrayList<NameValuePair>();
        if(map != null){
            Iterator<String> it = map.keySet().iterator();
            while(it.hasNext()){
                String key = it.next();
                String value = map.get(key);
                paramList.add(new BasicNameValuePair(key,value));
            }
        }
        return paramList;
    }

    private static void setHeader(HttpRequestBase request, Map<String,String> headMap){
        if(headMap != null){
            Iterator<String> it2 = headMap.keySet().iterator();
            while(it2.hasNext()){
                String key = it2.next();
                String value = headMap.get(key);
                request.setHeader(key,value);
            }
        }
    }

    /**带着cookie访问链接get*/
public static String get(String url,Map<String,String> map,Map<String,String> headMap){
    CloseableHttpResponse response = null;
    try {
        CloseableHttpClient client = HttpClients.createDefault();

        List<NameValuePair> getParams = getParamsList(map);

        URI uri = URIUtils.createURI(null, url, 0, null,
                URLEncodedUtils.format(getParams, "UTF-8"), null);
        HttpGet httpget = new HttpGet(uri);
        setHeader(httpget, headMap);

        response = client.execute(httpget);
        if(response.getStatusLine().getStatusCode() != 200){
            System.out.println(uri.toString() +"------>"+response.getStatusLine().getReasonPhrase());
        }
        InputStream content = response.getEntity().getContent();
        byte[] bytes = new byte[1024];
        int size = 0;
        StringBuilder sb = new StringBuilder();
        while ((size = content.read(bytes)) != -1){
            sb.append(new String(bytes,0,size));
        }
        System.out.println(sb.toString());
        return sb.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;

}




    /**不取带着cookie访问链接post*/

    public static CloseableHttpResponse post(String url, Map<String,String> map){
        CloseableHttpResponse response = null;
        try {
            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost post = new HttpPost();
            post.setURI(new URI(url));

            List<NameValuePair> paramList = getParamsList(map);

            UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(
                    paramList, "UTF-8");
            post.setEntity(postEntity);
            response = client.execute(post);
//            System.out.println(response.getAllHeaders());
            //执行后信息打印，流读取
//            StringBuilder text = new StringBuilder();
//            byte[] bytes = new byte[1024];
//            InputStream content = response.getEntity().getContent();
//            int size = 0;
//            while((size = content.read(bytes)) != -1){
//                text.append(new String(bytes,0,size));
//            }
//            System.out.println(text.toString());


        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }
}
